package com.sbio.udiapp.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.sbio.udiapp.BuildConfig;
import com.sbio.udiapp.adapter.OutStockApplyAdapter;
import com.sbio.udiapp.common.bean.RequestUniParam;
import com.sbio.udiapp.common.bean.UdiDataDownloadPage;
import com.sbio.udiapp.databinding.ActivityUdiDataDownloadBinding;
import com.sbio.udiapp.listener.ListAdapterListener;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.bean.AjaxResult;
import com.sbio.udiapp.util.ApiServiceUtil;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.IntentUtil;
import com.sbio.udiapp.util.LogUtil;
import com.sbio.udiapp.util.ToastUtil;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@AndroidEntryPoint
public class UdiDataDownloadActivity extends BaseBroadCastActivity implements ListAdapterListener {

    ActivityUdiDataDownloadBinding binding;

    @Inject
    ApiService apiService;

    ProgressDialog progressDialog;

    ObservableList<String> nos = new ObservableArrayList<>();

    UdiDataDownloadPage page = new UdiDataDownloadPage();

    private boolean needSavePage;


    /**
     * 用于上传时的数据
     */
    UdiDataDownloadPage pageCopy;

    OutStockApplyAdapter adapter;


    {
        page.setNos(nos);
        needSavePage = true;
    }


    /**
     * 初始化进度条
     */
    public void initProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载中..."); // 设置提示信息
        progressDialog.setCancelable(true); // 设置是否允许用户通过点击屏幕或按返回键取消对话框
        progressDialog.show(); // 显示对话框
    }

    public void showProcess() {
        progressCount.incrementAndGet();
        progressDialog.show();
    }

    public void hideProcess() {
        int count = progressCount.decrementAndGet();
        if (count <= 0) {
            progressDialog.hide();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUdiDataDownloadBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //初始化进度条
        initProgressDialog();

        //初始化页面
        initPageNo();

//        initSystemScanData();

        //初始化nos监听器
        initNosListener();

        initToggleDataWidget();

        //绑定提交业务
        bindSubmitEvent();
    }

    private void bindSubmitEvent() {
        binding.submit.setOnClickListener(v -> {

//            String requestUniParam = RequestUniParam.create("提交ExpressActivity").toJson();
            showProcess();

            ApiServiceUtil.enqueue(() -> apiService.getUdiDataDownloadCode(page.getPageNo()), new Callback<AjaxResult>() {
                @Override
                public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                    hideProcess();
                    try {
                        AjaxResult ajaxResult = response.body();
                        if (ajaxResult.getCode() == 500) {
                            ToastUtil.showError(ajaxResult.getMsg());
                            return;
                        }
                        if (ajaxResult.isSuccess()) {
                            ToastUtil.show("提交成功");
                            DialogUtil.showCommonAlertDialog(String.format("提交成功\n请前往https://filecodebox.s-sbio.com输入%s下载", ajaxResult.getData()), UdiDataDownloadActivity.this::reset);

                        } else {
                            DialogUtil.showCommonAlertDialog("提交失败失败：" + ajaxResult.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtil.file("print", e.getMessage());
                    }
                }

                @Override
                public void onFailure(Call<AjaxResult> call, Throwable t) {
                    hideProcess();
                    DialogUtil.showErrorAlertDialog(t.getMessage());
                }
            });
        });
    }


    @Override
    public void onBroadcastReceiver(String barcodeData) {
        LogUtil.file("接收到广播数据", barcodeData);
        if (progressCount.get() > 0) {
            ToastUtil.showWait("请等待上一个结果返回");
            return;
        }
        if (nos.contains(barcodeData)) {
            ToastUtil.showError("数据重复");
            return;
        }
        //如果是出库申请开头的数据那么就是outStockApplyNos
        if (barcodeData.indexOf("XM") == 0) {
            pageCopy = page.copy();
            pageCopy.getNos().add(barcodeData);
            saveUdiDataDownload(() -> nos.add(barcodeData));
        } else {
            //非法数据
            ToastUtil.showError("非法数据，请检查");
            return;
        }
    }

    /**
     * 保存页面数据
     */
    private void saveUdiDataDownload(Runnable r1) {
        String requestUniParam = RequestUniParam.create("保存页面数据").toJson();
        showProcess();

        ApiServiceUtil.enqueue(() -> apiService.saveUdiDataDownload(pageCopy), new Callback<AjaxResult>() {
            @Override
            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                hideProcess();
                AjaxResult ajaxResult = response.body();
                if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                    String count = ajaxResult.getData(String.class);
                    ToastUtil.showSuccess("保存成功");
                    Optional.ofNullable(r1).ifPresent(Runnable::run);
                } else {
                    DialogUtil.showErrorAlertDialog(ajaxResult.getMsg());
                }
            }

            @Override
            public void onFailure(Call<AjaxResult> call, Throwable t) {
                hideProcess();
                DialogUtil.showErrorAlertDialog(t.getMessage());
            }
        });
    }

    //初始化nos监听器
    private void initNosListener() {
        //初始化nos listView布局
        binding.nos.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OutStockApplyAdapter(nos, this);
        binding.nos.setAdapter(adapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider)); // 设置自定义分割线样式
        binding.nos.addItemDecoration(dividerItemDecoration);
        binding.nos.setItemAnimator(new DefaultItemAnimator());

        nos.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<String>>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onChanged(ObservableList<String> sender) {
                adapter.notifyDataSetChanged(); // 数据变化时通知适配器刷新列表
            }

            @Override
            public void onItemRangeChanged(ObservableList<String> sender, int positionStart, int itemCount) {
                adapter.notifyItemRangeChanged(positionStart, itemCount); // 通知适配器局部刷新
            }

            @Override
            public void onItemRangeInserted(ObservableList<String> sender, int positionStart, int itemCount) {
//                adapter.notifyItemRangeChanged(positionStart-1, itemCount); // 通知适配器局部刷新
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onItemRangeMoved(ObservableList<String> sender, int fromPosition, int toPosition, int itemCount) {
                adapter.notifyItemRangeRemoved(fromPosition, itemCount); // 通知适配器局部刷新
            }

            @Override
            public void onItemRangeRemoved(ObservableList<String> sender, int positionStart, int itemCount) {
                adapter.notifyItemRangeRemoved(positionStart, itemCount); // 通知适配器局部刷新
            }
        });
    }

    private void initPageNo() {
        showProcess();
        String requestUniParam = RequestUniParam.create("初始化页面编码").toJson();
        apiService.getNextPageNoByPageType("udd", requestUniParam).enqueue(new Callback<AjaxResult>() {
            @Override
            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                hideProcess();
                if (response.code() != 200) {
                    ToastUtil.show("获取页面编码失败,请退出页面重试");
                    return;
                }
                AjaxResult result = response.body();
                if (result.isSuccess()) {
                    String pageNo = result.getData(String.class);
                    binding.pageNoEdit.setText(pageNo);
                    page.setPageNo(pageNo);
                    LogUtil.file("获取页面编码", "pageNo:" + pageNo);
                }
                //初始化测试数据
                if (BuildConfig.DEBUG) {
//                    initTestData();
                }
            }

            @Override
            public void onFailure(Call<AjaxResult> call, Throwable t) {
                hideProcess();
//                ToastUtil.show("获取页面编码失败,请退出页面重试");
                DialogUtil.showErrorAlertDialog(t.getMessage());
            }
        });
    }

    @Override
    public void remove(String datum) {
        pageCopy = page.copy();
        pageCopy.getNos().remove(datum);
        saveUdiDataDownload(() -> nos.remove(datum));

    }

    private void initToggleDataWidget() {

        binding.toggleData.setOnClickListener(v -> {
            String pageNo = binding.pageNoEdit.getText().toString();
            showProcess();

            ApiServiceUtil.enqueue(() -> apiService.getUdiDataDownloadPage(pageNo), new Callback<AjaxResult>() {
                @Override
                public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                    hideProcess();
                    AjaxResult ajaxResult = response.body();
                    if (ajaxResult.isSuccess()) {
                        JSONObject data = ajaxResult.getData(JSONObject.class);
                        //暂时屏蔽同步
                        needSavePage = false;
                        nos.clear();
                        nos.addAll(data.getObject("data", List.class));
                        needSavePage = true;
                        //修改pageNo
                        page.setPageNo(pageNo);
                        ToastUtil.show("切换成功");
                    } else {
                        ToastUtil.show(ajaxResult.getMsg() + "，页面编码已重置");
                        binding.pageNoEdit.setText(page.getPageNo());
                    }
                }

                @Override
                public void onFailure(Call<AjaxResult> call, Throwable t) {
                    hideProcess();
                    DialogUtil.showErrorAlertDialog(t.getMessage());
                    binding.pageNoEdit.setText(page.getPageNo());
                }
            });
        });
    }

    private void reset() {

        showProcess();
        nos.clear();
        page = new UdiDataDownloadPage();
        page.setNos(nos);
        initPageNo();
        hideProcess();
    }

}